import { lazy,Suspense,FC } from 'react'
import { Navigate, useRoutes } from "react-router-dom";

interface Meta{
    title:string,
    isLogin:boolean
}
interface Props{
    meta:Meta,
    children:JSX.Element
}

const BeforeEach:FC<Props> = ({meta,children }) => {

    if(meta){
        document.title=meta.title;
    }

    if (!sessionStorage.getItem("token") && !meta.isLogin) {
        return (
            <Navigate to="/login" />
        )
    }
    else {
        return (
            children
        )
    }
}

const routes = [
    {
        path: '/',
        meta:{title:"首页"},
        component: lazy(() => import('../pages/Index')),
        children:[
            {path: '/', meta:{title:"首页"},component: lazy(() => import('../pages/Home')),},
            {path: 'fee', meta:{title:"缴费管理"},component: lazy(() => import('../pages/Fee')),},
            {path: 'userinfo', meta:{title:"居民管理"},component: lazy(() => import('../pages/Userinfo')),},
            {path: 'repairs', meta:{title:"报修管理"},component: lazy(() => import('../pages/Repairs')),},
            {path: 'questions', meta:{title:"投诉管理"},component: lazy(() => import('../pages/Questions')),},
            {path: 'staffs', meta:{title:"职员管理"},component: lazy(() => import('../pages/Staffs')),},
            {path: 'news', meta:{title:"公告管理"},component: lazy(() => import('../pages/News')),},
            {path: 'stores', meta:{title:"门店管理"},component: lazy(() => import('../pages/Stores')),},
            {path: 'building', meta:{title:"楼栋管理"},component: lazy(() => import('../pages/Building')),},
            {path: 'house', meta:{title:"房间管理"},component: lazy(() => import('../pages/House')),},
            {path: 'administrator', meta:{title:"管理员管理"},component: lazy(() => import('../pages/Administrator')),},
            {path: 'administratorrole', meta:{title:"角色管理"},component: lazy(() => import('../pages/Administratorrole')),},
            {path: 'advertisement', meta:{title:"图片管理"},component: lazy(() => import('../pages/Advertisement')),},
        ]
    },
    {
        path: '/login',
        meta:{title:"登录",isLogin:true},
        component: lazy(() => import('../pages/Login')),
    },

]


const getRouters = (routers:any) => {
    return routers.map((item:any) => {
      if (item.children) {
        item.children = getRouters(item.children)
      }
      item.element = <Suspense fallback={
        <div>加载中...</div>
      }>
        <BeforeEach meta={item.meta}><item.component /></BeforeEach>
      </Suspense>
      return item
    })
  }


const Routers= () => {

    const _routes=getRouters(routes);
   return useRoutes(_routes);

}
export default Routers;
